﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DiskClean
{
    public partial class Form1 : Form
    {
        private DiskManager dc = null;
        private List<string> drives = null;
        private AutoResetEvent copyDeletEvent = new AutoResetEvent(false);
        public Form1()
        {
            InitializeComponent();
            dc = new DiskManager();
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            drives = dc.GetAllDrives();
            SourceCbx.Items.AddRange(drives.ToArray());
            DestCmx.Items.AddRange(drives.ToArray());
            int drivenum = drives.Count;
            SourceCbx.SelectedIndex = 0;
            DestCmx.SelectedIndex = drivenum - 1;
            //ParentDirTest();
            UpdateTopDirList(dc.GetDirs(SourceCbx.Text));

            Stopwatch sw = new Stopwatch();
            sw.Start();
            DeepScanDestDir(DestCmx.Text,new Common.CopyOptions() { MaxDepth = 3 });
            sw.Stop();
            //MessageBox.Show("DeepScan completed in " + sw.ElapsedMilliseconds + "ms");
        }
        private void ParentDirTest()
        {
            ParentDirlistView.Items.Clear();
            ListViewItem item = new ListViewItem(new string[] { "ParentDir2" });
            ParentDirlistView.Items.Add(item);
        }
        private void UpdateSourceList(List<FileInfo> files,int num)
        {
            SourcelistView.Invoke(new Action(() =>
            {
                SourcelistView.Items.Clear();
                ListViewItem item = null;
                FileInfo file = null;
                num = Math.Min(num, files.Count);
                for (int i = 0; i < num; i++)
                {
                    file = files[i];
                    item = new ListViewItem(new string[] { file.Name, (file.Length*1.0/1024/1024).ToString("0.00")+"MB", file.FullName.ToString(), file.LastAccessTime.ToString() });
                    SourcelistView.Items.Add(item);
                }
            }));
        }
        private Dictionary<string, bool> GetIgnoreDir(ListView lv)
        {
            Dictionary<string, bool> ignoreDir = new Dictionary<string, bool>();
            foreach(ListViewItem item in lv.Items)
            {
                //item.Checked = true;
                ignoreDir.Add(item.Text, item.Checked);
            }
            return ignoreDir;
        }
        private void ScanBtn_Click(object sender, EventArgs e)
        {
            string drive = SourceCbx.Text;

            //UpdateTopDirList(dc.GetDirs(drive));
            Dictionary<string, bool> ignoreDir = GetIgnoreDir(ParentDirlistView);
            //test
            //Console.WriteLine(ParentDirlistView.Items[0].Checked);
            Common.Options options = new Common.Options();
            options.IsDeletEmptyDir = DeleteEmptyCheckBox.Checked;

            Task task = new Task(() =>
            {
                
                List<FileInfo> files = dc.GetFilesByDrive(drive, ignoreDir,options);
                int num = (int)ForwardNumericUpDown.Value;
                UpdateSourceList(files, num);
            });
            Stopwatch sw = new Stopwatch();
            sw.Start();
            task.ContinueWith((t) =>
            {
                sw.Stop();
                //MessageBox.Show("Scan completed in " + sw.ElapsedMilliseconds + "ms");
            });
            task.Start();
        }
        private void UpdateTopDirList(string[] dirs)
        {
            ParentDirlistView.Items.Clear();
            foreach (string dir in dirs)
            {
                ListViewItem item = new ListViewItem(new string[] { dir });
                ParentDirlistView.Items.Add(item);
            }
        }

        private void TestBtn_Click(object sender, EventArgs e)
        {
            if(ParentDirlistView.Items[0].Checked == true)
            {
                MessageBox.Show("ParentDir2");
            }
        }

        private void SourceCbx_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateTopDirList(dc.GetDirs(SourceCbx.Text));
        }

        private void SelectAllcheckBox_CheckedChanged(object sender, EventArgs e)
        {
            bool isChecked = SelectAllcheckBox.Checked;
            foreach (ListViewItem item in ParentDirlistView.Items)
            {
                item.Checked = isChecked;
            }
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            Console.WriteLine("DeleteBtn_Click Beging");
            List<string> files = new List<string>();
            foreach (ListViewItem item in SourcelistView.Items)
            {
                if (item.Checked)
                {
                    files.Add(item.SubItems[2].Text);
                }
            }
            Task task = new Task(() => {
                foreach (string file in files)
                {
                    File.Delete(file);
                }            
            });
            task.ContinueWith((t) =>
            {
                MessageBox.Show("Delete completed");
            });
            task.Start();
        }
        private void FileBackup()
        {
            List<string> files = new List<string>();
            string destDir = BackUpDirtextBox.Text;

            foreach (ListViewItem item in SourcelistView.Items)
            {
                if (item.Checked)
                {
                    files.Add(item.SubItems[2].Text);
                }
            }
            copyDeletEvent.Reset();
            Task task = new Task(() =>
            {                
                foreach (string file in files)
                {
                    File.Copy(file, Path.Combine(destDir, Path.GetFileName(file)));
                }                
            });
            task.ContinueWith((t) =>
            {
                copyDeletEvent.Set();
                Console.WriteLine("Backup completed");
            });
            task.Start();
        }
        private void BackUpDeleteBtn_Click(object sender, EventArgs e)
        {
            if(BackUpDirtextBox.Text == "")
            {
                MessageBox.Show("Please input backup directory");
                return;
            }
            FileBackup();
            copyDeletEvent.WaitOne();
            DeleteBtn_Click(sender, e);        
        }
        private  void DeepScanDestDir(string destDir,Common.CopyOptions options)
        {
            DestTreeView.Nodes.Clear();
            TreeNode rootNode = new TreeNode(destDir)
            {
                Tag = destDir
            };
            DestTreeView.Nodes.Add(rootNode);

            LoadTreeNodes(rootNode, options.MaxDepth, 0);
        }
        private void LoadTreeNodes(TreeNode node,int maxDepth = 3,int currentDepth = 0)
        {
            if (currentDepth >= maxDepth)
            {
                return;
            }
            string path = node.Tag.ToString();
            try
            {
                // 获取目录下的子目录
                string[] subDirs = Directory.GetDirectories(path);
                foreach (string dir in subDirs)
                {
                    // 为每个子目录创建一个 TreeNode
                    TreeNode dirNode = new TreeNode(Path.GetFileName(dir))
                    {
                        Tag = dir
                    };
                    node.Nodes.Add(dirNode);

                    // 递归加载子目录的内容
                    LoadTreeNodes(dirNode, maxDepth, currentDepth + 1);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void DestCmx_SelectedIndexChanged(object sender, EventArgs e)
        {
            DeepScanDestDir(DestCmx.Text,new Common.CopyOptions() { MaxDepth = 3 });
        }

        private void DestTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            BackUpDirtextBox.Text = "";
            BackUpDirtextBox.Text = e.Node.Tag.ToString();
        }

        private void SourcelistView_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListViewItem item = SourcelistView.GetItemAt(e.X, e.Y);
                if (item != null)
                {
                    ListViewHitTestInfo info = SourcelistView.HitTest(e.X, e.Y);
                    if (info.SubItem != null)
                    {
                        //MessageBox.Show(info.SubItem.Text);
                        DialogResult result = MessageBox.Show(info.SubItem.Text, "Open file in Directory?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        if (result == DialogResult.OK)
                        {
                            OpenFileDirectory(info.SubItem.Text);
                        }
                    }
                }
            }
        }
        public void OpenFileDirectory(string filePath)
        {
            if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
            {
                string directoryPath = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(directoryPath))
                {
                    Process.Start(directoryPath);
                }
                else
                {
                   MessageBox.Show("文件路径无效");
                }
            }
            else
            {
                MessageBox.Show("文件不存在");
            }
        }
    }
}
